#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <qcombobox.h>
#include <qlogging.h>
#include <qobject.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);

  cmbs.append(ui->cmb_baud);
  cmbs.append(ui->cmb_check);
  cmbs.append(ui->cmb_data);
  cmbs.append(ui->cmb_flow);
  cmbs.append(ui->cmb_stop);

  for (QComboBox *cmb : cmbs) {
    cmb->setEnabled(true);
  }

  setLedColor(ui->led_1, "ff0000", 20);
  setLedColor(ui->led_2, "ff0000", 20);
  setLedColor(ui->led_3, "ff0000", 20);

  ui->label_switch_1->setVisible(false);
  ui->label_switch_1->setText("0");

  ui->txt_rec_1->setReadOnly(true);
  ui->txt_rec_2->setReadOnly(true);
  ui->txt_rec_3->setReadOnly(true);
  ui->txt_msg->setReadOnly(true);

  ui->btn_send_1->setEnabled(false);
  ui->btn_send_2->setEnabled(false);
  ui->btn_send_3->setEnabled(false);

  // 串口号
  for (int i = 1; i <= 20; i++) {
    ui->cmb_port_1->addItem(QString("COM%1").arg(i));
    ui->cmb_port_2->addItem(QString("COM%1").arg(i));
    ui->cmb_port_3->addItem(QString("COM%1").arg(i));
  }

  ui->cmb_port_1->setCurrentIndex(0);
  ui->cmb_port_2->setCurrentIndex(1);
  ui->cmb_port_3->setCurrentIndex(2);

  // 波特率
  ui->cmb_baud->addItem(QString("1200"), QSerialPort::Baud1200);
  ui->cmb_baud->addItem(QString("2400"), QSerialPort::Baud2400);
  ui->cmb_baud->addItem(QString("4200"), QSerialPort::Baud4800);
  ui->cmb_baud->addItem(QString("9600"), QSerialPort::Baud9600);
  ui->cmb_baud->addItem(QString("19200"), QSerialPort::Baud19200);
  ui->cmb_baud->addItem(QString("38400"), QSerialPort::Baud38400);
  ui->cmb_baud->addItem(QString("57600"), QSerialPort::Baud57600);
  ui->cmb_baud->addItem(QString("115200"), QSerialPort::Baud115200);
  ui->cmb_baud->setCurrentIndex(7);

  // 数据位

  ui->cmb_data->addItem("8", QSerialPort::Data8);
  ui->cmb_data->addItem("7", QSerialPort::Data7);
  ui->cmb_data->addItem("6", QSerialPort::Data6);
  ui->cmb_data->addItem("5", QSerialPort::Data5);

  // 校验位
  ui->cmb_check->addItem("NONE", QSerialPort::NoParity);
  ui->cmb_check->addItem("ODD", QSerialPort::OddParity);
  ui->cmb_check->addItem("EVEN", QSerialPort::EvenParity);
  ui->cmb_check->addItem("MARK", QSerialPort::MarkParity);
  ui->cmb_check->addItem("SPACE", QSerialPort::SpaceParity);

  // 停止位
  ui->cmb_stop->addItem("1", QSerialPort::OneStop);
  ui->cmb_stop->addItem("1.5", QSerialPort::OneAndHalfStop);
  ui->cmb_stop->addItem("2", QSerialPort::TwoStop);

  // 流控制
  ui->cmb_flow->addItem("NONE", QSerialPort::NoFlowControl);
  ui->cmb_flow->addItem("RTS/CTS", QSerialPort::HardwareControl);
  ui->cmb_flow->addItem("XON/XOFF", QSerialPort::SoftwareControl);

  // 串口有数据
  connect(&sp1, &QSerialPort::readyRead, this, &MainWindow::spReadData_1);
  connect(&sp2, &QSerialPort::readyRead, this, &MainWindow::spReadData_2);
  connect(&sp3, &QSerialPort::readyRead, this, &MainWindow::spReadData_3);
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::setLedColor(QLabel *label, QString str, int size) {

  label->setText("");
  QString min_width = QString("min-width: %1px;").arg(size);
  QString min_height = QString("min-height: %1px;").arg(size);
  QString max_width = QString("max-width: %1px;").arg(size);
  QString max_height = QString("max-height: %1px;").arg(size);

  QString border_radius = QString("border-radius: %1px;").arg(size / 2);
  QString border = QString("border:0px solid black;");

  QString background = "background-color:#" + str;

  const QString Sheetstyle1 = min_width + min_height + max_width + max_height +
                              border_radius + border + background;
  label->setStyleSheet(Sheetstyle1);
}

void MainWindow::on_btn_clear_1_clicked() { ui->txt_rec_1->clear(); }
void MainWindow::on_btn_clear_2_clicked() { ui->txt_rec_2->clear(); }
void MainWindow::on_btn_clear_3_clicked() { ui->txt_rec_3->clear(); }
void MainWindow::on_btn_clear_4_clicked() { ui->txt_msg->clear(); }

void MainWindow::on_cmb_port_1_currentTextChanged(QString str) {
  ui->groupBox_1->setTitle(str);
}
void MainWindow::on_cmb_port_2_currentTextChanged(QString str) {
  ui->groupBox_2->setTitle(str);
}
void MainWindow::on_cmb_port_3_currentTextChanged(QString str) {
  ui->groupBox_3->setTitle(str);
}

void MainWindow::spReadData_1() {
  QString strTime =
      QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz: ");
  ui->txt_rec_1->appendPlainText(strTime + QString(sp1.readAll()));
}
void MainWindow::spReadData_2() {
  QString strTime =
      QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz: ");
  ui->txt_rec_2->appendPlainText(strTime + QString(sp2.readAll()));
}
void MainWindow::spReadData_3() {
  QString strTime =
      QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz: ");
  ui->txt_rec_3->appendPlainText(strTime + QString(sp3.readAll()));
}

void MainWindow::on_btn_switch_clicked() {
  // 表示此刻串口总开关处于关闭状态，点击打总开关
  if (ui->label_switch_1->text() == "0") {

    // 不管各个串口打开成功与否，反正总开关已开启
    ui->label_switch_1->setText("1");
    ui->btn_switch->setText("ON");

    // 打开串口1
    sp1.setPortName(ui->cmb_port_1->currentText());
    sp1.setBaudRate(ui->cmb_baud->currentText().toInt());
    sp1.setParity((QSerialPort::Parity)ui->cmb_check->currentData().toInt());
    sp1.setDataBits((QSerialPort::DataBits)ui->cmb_data->currentData().toInt());
    sp1.setStopBits((QSerialPort::StopBits)ui->cmb_stop->currentData().toInt());
    sp1.setFlowControl(
        (QSerialPort::FlowControl)ui->cmb_flow->currentData().toInt());
    isOpen_1 = sp1.open(QIODevice::ReadWrite);

    // 打开串口2
    sp2.setPortName(ui->cmb_port_2->currentText());
    sp2.setBaudRate(ui->cmb_baud->currentText().toInt());
    sp2.setParity((QSerialPort::Parity)ui->cmb_check->currentData().toInt());
    sp2.setDataBits((QSerialPort::DataBits)ui->cmb_data->currentData().toInt());
    sp2.setStopBits((QSerialPort::StopBits)ui->cmb_stop->currentData().toInt());
    sp2.setFlowControl(
        (QSerialPort::FlowControl)ui->cmb_flow->currentData().toInt());
    isOpen_2 = sp2.open(QIODevice::ReadWrite);

    // 打开串口3
    sp3.setPortName(ui->cmb_port_3->currentText());
    sp3.setBaudRate(ui->cmb_baud->currentText().toInt());
    sp3.setParity((QSerialPort::Parity)ui->cmb_check->currentData().toInt());
    sp3.setDataBits((QSerialPort::DataBits)ui->cmb_data->currentData().toInt());
    sp3.setStopBits((QSerialPort::StopBits)ui->cmb_stop->currentData().toInt());
    sp3.setFlowControl(
        (QSerialPort::FlowControl)ui->cmb_flow->currentData().toInt());
    isOpen_3 = sp3.open(QIODevice::ReadWrite);

    // 判断串口1打开是否成功
    if (isOpen_1) {

      ui->cmb_port_1->setEnabled(false);
      ui->txt_msg->appendPlainText(
          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
      ui->txt_msg->appendPlainText("  " + ui->cmb_port_1->currentText() +
                                   "已打开！");

      QString str = "     波特率:" + ui->cmb_baud->currentText() + "\n" +
                    "     数据位:" + ui->cmb_data->currentText() + "\n" +
                    "     停止位:" + ui->cmb_stop->currentText() + "\n" +
                    "     校验位:" + ui->cmb_check->currentText() + "\n" +
                    "     流控制:" + ui->cmb_flow->currentText() + "\n";

      ui->txt_msg->appendPlainText(str);

      ui->btn_send_1->setEnabled(true);

      setLedColor(ui->led_1, "33ff00", 20);

    } else { // 串口打开失败
      ui->cmb_port_1->setEnabled(true);
      setLedColor(ui->led_1, "ff0000", 20);
      ui->txt_msg->appendPlainText("  " + ui->cmb_port_1->currentText() +
                                   "开启失败，" + sp1.errorString() + "\n");
      ui->btn_send_1->setEnabled(false);
    }
    // 判断串口2打开是否成功
    if (isOpen_2) {
      ui->cmb_port_2->setEnabled(false);
      ui->txt_msg->appendPlainText(
          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
      ui->txt_msg->appendPlainText("  " + ui->cmb_port_2->currentText() +
                                   "已打开！");

      QString str = "   波特率:" + ui->cmb_baud->currentText() + "\n" +
                    "   数据位:" + ui->cmb_data->currentText() + "\n" +
                    "   停止位:" + ui->cmb_stop->currentText() + "\n" +
                    "   校验位:" + ui->cmb_check->currentText() + "\n" +
                    "   流控制:" + ui->cmb_flow->currentText() + "\n";

      ui->txt_msg->appendPlainText(str);

      setLedColor(ui->led_2, "33ff00", 20);

    } else { // 表示此刻串口打开失败
      ui->cmb_port_2->setEnabled(true);

      setLedColor(ui->led_2, "ff0000", 20);

      ui->txt_msg->appendPlainText(
          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
      ui->txt_msg->appendPlainText("  " + ui->cmb_port_2->currentText() +
                                   "开启失败，" + sp2.errorString() + "\n");

      ui->btn_send_2->setEnabled(true);
    }

    // 判断串口3打开是否成功
    if (isOpen_3) {
      ui->cmb_port_3->setEnabled(false);
      ui->txt_msg->appendPlainText(
          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
      ui->txt_msg->appendPlainText("  " + ui->cmb_port_3->currentText() +
                                   "已打开！");

      QString str = "     波特率:" + ui->cmb_baud->currentText() + "\n" +
                    "     数据位:" + ui->cmb_data->currentText() + "\n" +
                    "     停止位:" + ui->cmb_stop->currentText() + "\n" +
                    "     校验位:" + ui->cmb_check->currentText() + "\n" +
                    "     流控制:" + ui->cmb_flow->currentText() + "\n";

      ui->txt_msg->appendPlainText(str);

      ui->btn_send_3->setEnabled(true);

      setLedColor(ui->led_3, "33ff00", 20);

    } else { // 串口打开失败
      ui->cmb_port_3->setEnabled(true);
      ui->txt_msg->appendPlainText(
          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
      setLedColor(ui->led_3, "ff0000", 20);
      ui->txt_msg->appendPlainText("  " + ui->cmb_port_3->currentText() +
                                   "开启失败，" + sp3.errorString() + "\n");
      ui->btn_send_3->setEnabled(false);
    }

  } else {

    // 关闭串口总开关
    sp1.close();
    sp2.close();
    sp3.close();

    ui->label_switch_1->setText("0");
    ui->btn_switch->setText("OFF");

    ui->cmb_port_1->setEnabled(true);
    ui->cmb_port_2->setEnabled(true);
    ui->cmb_port_3->setEnabled(true);

    setLedColor(ui->led_1, "ff0000", 20);
    setLedColor(ui->led_2, "ff0000", 20);
    setLedColor(ui->led_3, "ff0000", 20);

    ui->txt_msg->appendPlainText(
        QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
    ui->txt_msg->appendPlainText("  " + ui->cmb_port_1->currentText() +
                                 "已关闭！");
    ui->txt_msg->appendPlainText("  " + ui->cmb_port_2->currentText() +
                                 "已关闭！");
    ui->txt_msg->appendPlainText("  " + ui->cmb_port_3->currentText() +
                                 "已关闭!\n");
  }
}

void MainWindow::on_btn_send_1_clicked() {
  sp1.write(ui->lineEdit_1->text().toUtf8());
}

void MainWindow::on_btn_send_2_clicked() {
  sp2.write(ui->lineEdit_2->text().toUtf8());
}
void MainWindow::on_btn_send_3_clicked() {
  sp3.write(ui->lineEdit_3->text().toUtf8());
}

void MainWindow::on_btn_save_1_clicked() { saveFile(); }
void MainWindow::on_btn_save_2_clicked() { saveFile(); }
void MainWindow::on_btn_save_3_clicked() { saveFile(); }

void MainWindow::saveFile() {
  QString fileName = QFileDialog::getSaveFileName(
      this, "保存文件", "", "Text (*.txt);;Excel (*.xlsx);;Dat (*.dat)");

  if (!fileName.isEmpty()) {
    // 如果用户选择了文件路径，则保存数据到文件
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly)) {
      QMessageBox::warning(nullptr, "错误", "无法打开文件!");
      return;
    }
    QTextStream out(&file);
    out << ui->txt_rec_1->toPlainText();
    file.close();
  }
}